using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Domain.EWE;
using SmartTracking.Infrastructure.Interfaces;
using AutoMapper;
using Yitter.IdGenerator;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;

namespace SmartTracking.ApiWrite.Applications.Commands.Ewemating
{
    /// <summary>
    /// 批量添加母羊配种处理器
    /// </summary>
    public class AddBatchWeaningsCommandHandler : IRequestHandler<AddBatchWeaningsCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Weanings> eRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<MainWeaning> mRep;
        public AddBatchWeaningsCommandHandler(IBaseRepository<Weanings> eRep, IMapper mapper, IBaseRepository<MainWeaning> mRep)
        {
            this.eRep = eRep;
            this.mapper = mapper;
            this.mRep = mRep;
        }

        public async Task<ApiResult<int>> Handle(AddBatchWeaningsCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            
            if (request.WeaningsList == null || request.WeaningsList.Count == 0)
            {
                result.Code = ApiEnum.新增失败;
                result.Message = "参数错误，配种数据列表不能为空";
                return result;
            }

            try
            {
                List<Weanings> ewematingsList = new List<Weanings>();
                MainWeaning ma = new MainWeaning();
                ma.ResponsibleFor = request.ResponsibleFor;
                ma.MainWeaningTime = request.MainWeaningTime;
                ma.DocumentNumber = request.DocumentNumber;
                ma.SerialNumber = request.SerialNumber;
                await mRep.AddAsync(ma);
                foreach (var item in request.WeaningsList)
                {
                    Weanings ewemating = mapper.Map<Weanings>(item);
                    //ewemating.EwematingSnowId = YitIdHelper.NextId().ToString();
                    ewematingsList.Add(ewemating);
                }

                int affectedRows = await eRep.AddRangeAsync(ewematingsList);
                
                if (affectedRows > 0)
                {
                    result.Code = ApiEnum.新增成功;
                    result.Message = $"批量添加成功，共添加{affectedRows}条记录";
                    result.data = affectedRows;
                }
                else
                {
                    result.Code = ApiEnum.新增失败;
                    result.Message = "批量添加失败";
                }
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.新增失败;
                result.Message = "批量添加过程中发生错误：" + ex.Message;
            }

            return result;
        }
    }
}